<template>
  <div class="edit-dish-container">
    <el-form
      :model="form"
      ref="form"
      label-width="120px"
      :rules="rules"
      class="form-container"
    >
      <el-form-item label="菜品名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入菜品名称"></el-input>
      </el-form-item>

      <el-form-item label="菜品分类:" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择菜品分类">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="菜品价格:" prop="price">
        <el-input v-model="form.price" placeholder="请设置菜品价格"></el-input>
      </el-form-item>

      <el-form-item label="口味做法配置:">
        <el-button
          @click="favorShow = true"
          icon="el-icon-plus"
          type="warning"
          v-show="!favorShow"
          >添加口味</el-button
        >
        <div class="flavorBox" v-show="favorShow">
          <div class="flavor">
            <div class="title">
              <span>口味名（3个字内）</span
              ><span>口味标签（输入标签回车添加）</span>
            </div>
            <!-- 中间可以增减的 -->
            <div
              v-for="(item, index) in flavorList"
              :key="index"
              class="input-box"
            >
              <el-autocomplete
                class="first-input"
                v-model="item.input1"
                :fetch-suggestions="querySearch"
                placeholder="请输入口味"
                @select="handleSelect"
              ></el-autocomplete>
              <el-input
                placeholder="请输入内容"
                v-model="item.input2"
                class="second-input"
                @keyup.native.enter="addTag(index)"
                @keydown.enter.native.prevent
                clearable
              >
                <template slot="prepend" v-if="item.input1">
                  <div class="tag-container">
                    <el-tag
                      v-for="(tag, order) in tags[index]"
                      :key="order"
                      closable
                      @close="removeTag(order, index)"
                      type="warning"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </template>
              </el-input>
              <!-- 右侧删除按钮 -->
              <el-link type="danger" @click="deleteRow(index)">删除</el-link>
            </div>
            <!-- 底部添加口味按钮 -->
            <div class="button">
              <el-button type="warning" @click="addRow">添加口味</el-button>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="菜品图片:" prop="image">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:9528/dev-api/common/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="菜品描述:">
        <!-- <el-input v-model="form.description"></el-input> -->
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入菜品描述"
          v-model="form.description"
          class="description"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <div class="bottom-buttons">
      <el-button type="default" @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script>
import { getList, getForm, changeDishes, addDishes } from "@/api/dishManage";
export default {
  data() {
    return {
      form: {
        name: "",
        categoryId: "",
        price: "",
        description: "",
        flavors: [],
        image: "",
        code: "",
        status: 1,
      },
      rules: {
        categoryId: [
          { required: true, message: "请选择菜品分类", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
        price: [{ required: true, message: "请设置菜品价格", trigger: "blur" }],
        image: [
          { required: true, message: "请上传菜品图片", trigger: "change" },
        ],
      },

      //下拉框选项
      options: [],
      //图片上传
      imageUrl: "",
      //口味配置
      favorShow: false,
      state1: "",
      input3: "",
      favors: [
        { value: "甜味", options: ["无糖", "少糖", "半糖", "全糖"] },
        {
          value: "温度",
          options: ["热饮", "常温", "去冰", "少冰"],
        },
        {
          value: "忌口",
          options: ["不要葱", "不要香菜", "不要辣", "不要蒜"],
        },
        { value: "辣度", options: ["不辣", "微辣", "中辣", "重辣"] },
      ],
      flavorList: [{ input1: "", input2: "" }],
      tags: [],
    };
  },
  async created() {
    this.getList(); //获取菜品分类下拉框选项
    if (this.isEdit) {
      const { data } = await getForm(this.$route.query.id);
      console.log("this.$route.query.id", this.$route.query.id);
      console.log("data", data);
      this.form = data;
    }
  },
  computed: {
    isEdit() {
      return this.$route.query.isEdit === "1";
    },
  },
  methods: {
    //口味做法
    addRow() {
      this.flavorList.push({ input1: "", input2: "" });
    },

    deleteRow(index) {
      if (this.flavorList.length === 1) {
        this.flavorList = [{ input1: "", input2: "" }];
        this.tags = [];
        this.favorShow = false;
      } else {
        this.flavorList.splice(index, 1);
        this.tags.splice(index, 1);
      }
    },
    addTag(index) {
      const trimmedValue =
        this.flavorList[this.flavorList.length - 1].input2.trim();
      if (trimmedValue && !this.tags[index].includes(trimmedValue)) {
        this.tags[index].push(trimmedValue);
        this.flavorList[this.flavorList.length - 1].input2 = ""; // 清空输入框
      }
    },
    removeTag(order, index) {
      this.tags[index].splice(order, 1); // 删除标签
    },

    handleSelect(item) {
      console.log(item);
      let arr = [...item.options];
      this.tags.push(arr);
    },
    querySearch(queryString, cb) {
      var favors = this.favors;
      var results = queryString
        ? favors.filter(this.createFilter(queryString))
        : favors;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (favor) => {
        return (
          favor.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    //获取菜品分类下拉框选项
    async getList() {
      const res = await getList(1);
      console.log("res", res);
      this.options = res.data;
    },
    //取消按钮
    handleCancel() {
      this.$router.go(-1);
    },
    //保存按钮
    handleSave() {
      console.log("this.form", this.form);
      console.log("this.flavorList", this.flavorList);
      console.log("this.tags", this.tags);
      this.form.price = this.form.price * 100;
      for (let i = 0; i < this.flavorList.length; i++) {
        let obj = {};
        obj.name = this.flavorList[i].input1;
        obj.value = `${this.tags[i]}`;
        obj.showOption = false;
        this.form.flavors.push(obj);
      }
      console.log("this.form", this.form);
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.isEdit) {
            delete this.form.updateTime;
            console.log("this.form", this.form);
            await changeDishes(this.form);
          } else {
            await addDishes(this.form);
          }
          this.$router.push({
            name: "DishManagement",
          });
          this.$message.success("修改成功");
        } else {
          return false;
        }
      });
    },

    //图片上传
    handleAvatarSuccess(res, file) {
      //   console.log("res", res);
      //   console.log("file", file);
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.image = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss">
.edit-dish-container {
  .form-container {
    width: 80%;
    padding: 20px;
    margin-left: 80px;

    .el-form-item__content {
      margin-bottom: 20px;

      .el-input {
        width: 300px;
      }

      //口味配置
      .flavorBox {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        padding: 15px;
        border: 1px solid #ccc;
        border-radius: 10px;
        background-color: #fafafb;

        .flavor {
          width: 100%;

          .title {
            font-size: 16px;
          }

          //中间可增加删除
          //   .input-box {
          //     width: 100%;
          //     display: flex;
          //     justify-content: space-between;
          //   }
          .input-box {
            width: 100%;
            display: grid;
            grid-template-columns: 1.5fr 4fr 0.5fr;
            gap: 10px;

            .second-input {
              width: calc(100% - 10px);

              .el-input-group__prepend {
                background-color: #fff;
                border-right: 0px !important;
              }
            }
          }

          //底部添加口味按钮
          .button {
            margin-top: 10px;
          }
        }
      }

      //上传图片
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9 !important;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d !important;
          width: 178px;
          height: 178px;
          line-height: 178px;
          text-align: center;
        }
        .avatar {
          width: 178px;
          height: 178px;
          display: block;
        }
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff !important;
      }

      //菜品描述
      .description {
        width: 100%;
      }
    }
  }

  .bottom-buttons {
    display: flex;
    justify-content: center;
  }
}
</style>
